package cc.booku.owlbox.OnlineDatabase;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wyt.searchbox.SearchFragment;
import com.wyt.searchbox.custom.IOnSearchClickListener;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.UnSearchPage.SearchListActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OnlineDatabaseActivity extends AppCompatActivity implements IOnSearchClickListener {
    private Toolbar Toolbar;
    private TextView tv_json;
    private NoScrollGridView lv_classity;
    private SearchFragment searchFragment;
    private List<Classity_C> classityCList = new ArrayList<Classity_C>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_database);
        lv_classity = (NoScrollGridView) findViewById(R.id.lv_classity);
        tv_json = (TextView) findViewById(R.id.tv_json);
//接收传过来的数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String SpecifiedFile = bundle.getString("SpecifiedFile");
        String OwlTitle = bundle.getString("OwlTitle");
        // 解析json
        JSONObject objsd = JSONObject.parseObject(FileoOperations.readFromSDFile(this, SpecifiedFile));
        String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
        String DecryptionAddress = Decrypt.RsaDecrypt(OnlineDatabaseActivity.this, ciphertext);
        String custabnav = objsd.getString("CUSTABNAV");//分类
        String cuslaypage = objsd.getString("CUSLAYPAGE");//分页
        String cussearch = objsd.getString("CUSSEARCH");//搜索


        tv_json.setText(ciphertext);

        //加载标题栏
        LoadToolbar(OwlTitle);

        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));

//
//        Toolbar = (Toolbar) findViewById(R.id.toolbar);
//        Toolbar.setTitle(OwlTitle);//标题
//        setSupportActionBar(Toolbar);
//
//        searchFragment = SearchFragment.newInstance();
//
//        Toolbar.setOnMenuItemClickListener(this);
//


        //读取地址和分类

        //页内导航
        init_classitylist(DecryptionAddress + custabnav);
    }


    private void LoadToolbar(String str) {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        searchFragment = SearchFragment.newInstance();
        searchFragment.setOnSearchClickListener(this);
        // searchFragment.setOnSearchClickListener();
        Toolbar.setTitle(str);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar

//        Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        Toolbar.inflateMenu(R.menu.menu_search);
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_search:
                        searchFragment.showFragment(getSupportFragmentManager(), SearchFragment.TAG);
                        break;
                }
                return true;
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void OnSearchClick(String keyword) {
        // searchInfo.setText(keyword);
        //Log.d("1111", "onFailure: "+keyword);

        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String SpecifiedFile = bundle.getString("SpecifiedFile");
        // 解析json
        JSONObject objsd = JSONObject.parseObject(FileoOperations.readFromSDFile(this, SpecifiedFile));
        String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
        String DecryptionAddress = Decrypt.RsaDecrypt(OnlineDatabaseActivity.this, ciphertext);
        String cussearch = objsd.getString("CUSSEARCH");//搜索

        try {

            //刷新
            Intent intent = new Intent();
            Bundle bundle2 = new Bundle();
            bundle2.putString("SearchData", keyword);
            bundle2.putString("DecryptionAddress", DecryptionAddress + cussearch);
            intent.putExtras(bundle2);
            intent.setClass(OnlineDatabaseActivity.this, cc.booku.owlbox.OnlineDatabase.SearchListActivity.class);
            startActivity(intent);

        } catch (Exception e) {

            Toast.makeText(OnlineDatabaseActivity.this, "程序异常", Toast.LENGTH_SHORT).show();
//异常处理
        }


    }


    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case 24:
                    classityClickData((ArrayList<Classity_C>) classityCList);
                    break;


            }
        }
    };


    private Classity_C classityC;

    public void init_classitylist(String Surl_file) {

        classityCList.clear();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
        //可以省略，默认是GET请求
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("1111", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsoninfo = response.body().string();


                //String jsonstr3 = jsonstr2.replace("$$$在线播放$", "|");


                ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
                StringBuffer stringBuffer = new StringBuffer();
                String str = null;
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                //03.使用fastJson解析Json、
                List<Classity_C> subc = JSON.parseArray(stringBuffer.toString(), Classity_C.class);
                for (Classity_C pp : subc) {
                    classityC = new Classity_C();
                    String count = pp.getCount();
                    String vod_class = pp.getVod_class();

                    // Log.d("ImageviewHolder", "显示图片url======" + vod_class);

                    classityC.setCount(count);
                    classityC.setVod_class(vod_class);

                    //pfilmclass.setParea(carea);
                    //将结果添加到对象集合中
                    classityCList.add(classityC);
                }

                Message msg = new Message();
                msg.what = 24;
                Thandler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

    }


    private Classity_A classityA;

    public void classityClickData(ArrayList<Classity_C> classityCArrayList) {

        classityA = new Classity_A(R.layout.online_classity_item, OnlineDatabaseActivity.this, classityCArrayList);


        lv_classity.setAdapter(classityA);
        lv_classity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //Toast.makeText(getContext(), "Click item" + i, Toast.LENGTH_SHORT).show();
                final TextView vod_class = (TextView) view.findViewById(R.id.vod_class);//名称
                final TextView count = (TextView) view.findViewById(R.id.count);//数量


                Bundle bundle = getIntent().getExtras();
                //接收name值
                String SpecifiedFile = bundle.getString("SpecifiedFile");
                // 解析json
                JSONObject objsd = JSONObject.parseObject(FileoOperations.readFromSDFile(OnlineDatabaseActivity.this, SpecifiedFile));
                String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
                String DecryptionAddress = Decrypt.RsaDecrypt(OnlineDatabaseActivity.this, ciphertext);
                String cuslaypage = objsd.getString("CUSLAYPAGE");//分页


                String vod_class1 = vod_class.getText().toString();
                String count1 = count.getText().toString();
                Intent intent = new Intent();
                Bundle bundle2 = new Bundle();
                bundle2.putString("vod_class1", vod_class1);
                bundle2.putString("laypage_api", DecryptionAddress + cuslaypage);
                bundle2.putString("count1", count1);
                intent.putExtras(bundle2);
                intent.setClass(OnlineDatabaseActivity.this, LayPageActivity.class);
                startActivity(intent);

                // Log.i("test======", "===gather_name1===" + vod_class1 + "===gather_url1===" + count1);


            }
        });


    }

}
